package cl.utalca.robot.web;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cl.utalca.robot.domain.LanguageDTO;
import cl.utalca.robot.domain.TestCaseDTO;
import cl.utalca.robot.domain.TestDTO;
import cl.utalca.robot.domain.TestResultDTO;
import cl.utalca.robot.domain.UploadItem;
import cl.utalca.robot.service.LanguageService;
import cl.utalca.robot.service.RobotService;
import cl.utalca.robot.service.TestCasesService;


@Controller
public class RobotController {

	private static final Logger logger = LoggerFactory.getLogger(RobotController.class); 
	
	@Autowired
	LanguageService languageService;
	
	@Autowired
	TestCasesService testCasesService;
	
	@Autowired
	RobotService robotService;
		
	@RequestMapping(value = "/test", method = RequestMethod.GET)
	public String  goTest(Model model){
		
		model.addAttribute("languageList", languageService.getLanguages());
		model.addAttribute(new UploadItem());
		return "test";
	}
	
	@RequestMapping(value = "/test", method = RequestMethod.POST)
	public String  doTest(UploadItem uploadItem, BindingResult result, Model model){
		
		LanguageDTO selectedLanguage = languageService.getLanguage(Integer.valueOf(uploadItem.getLanguageId()));

		//Creating the file in disk
		File fileUploaded = new File("/tmp", uploadItem.getFile().getOriginalFilename());
		try {
			FileUtils.writeByteArrayToFile(fileUploaded, uploadItem.getFile().getBytes());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		logger.debug(selectedLanguage.getLanguageName());
		List<TestCaseDTO> testCasesList = testCasesService.createTestCaseList("01");

		TestDTO program = new TestDTO(selectedLanguage, "Hola", fileUploaded.getName(), fileUploaded, testCasesList);
		TestResultDTO testResult = robotService.doTest(program);
		
		if(!testResult.getHasCompilationError())
			return "error";
		
		model.addAttribute("success", testResult.getSuccess());
		model.addAttribute("testCasesResults", testResult.getTestCasesResults());

		return "result";
	}
}
